import { DataTypes } from "sequelize";
import sequelize from "./db";
import { Op } from "sequelize";
const EmailCodeModel = sequelize.define("email_code", {
  email: {
    type: DataTypes.STRING(50),
    primaryKey: false,
    allowNull: false,
    comment: "邮箱"
  },
  code: {
    type: DataTypes.STRING(6),
    allowNull: false,
  },
  status: {
    type: DataTypes.INTEGER,
    allowNull: false,
    comment: "0，可用。1，不可用",
    defaultValue: 0
  },
  ext_data: {
    type: DataTypes.TEXT,
    allowNull: true,
    defaultValue: ""
  }
}, {
  hooks: {
    afterCreate(emailCode) {
      // 在每一次创建之后，将之前的验证码全部设置为不可用。
      const obj = emailCode.toJSON()

      EmailCodeModel.update({
        status: 1
      }, {
        where: {
          email: obj.email,
          id: {
            [Op.ne]: obj.id
          }
        },

      })
    }
  }
})

export default EmailCodeModel
